package cn.tedu.blog.server.service.impl;

import cn.tedu.blog.server.exception.ServiceException;
import cn.tedu.blog.server.mapper.CategoryMapper;
import cn.tedu.blog.server.pojo.dto.CategoryAddDTO;
import cn.tedu.blog.server.pojo.dto.CategoryAddNewDTO;
import cn.tedu.blog.server.pojo.entity.Category;
import cn.tedu.blog.server.pojo.vo.CategoryDetailVO;
import cn.tedu.blog.server.pojo.vo.CategoryListVO;
import cn.tedu.blog.server.repo.ICategoryRepository;
import cn.tedu.blog.server.service.ICategoryService;
import cn.tedu.blog.server.utils.OssUtils;
import cn.tedu.blog.server.utils.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static cn.tedu.blog.server.repo.ICategoryRepository.KEY_CATEGORY_LIST;

/**
 * @Author: 雷茂林
 * @Date:2022/7/17 10:02
 * @Description:
 */
@Slf4j
@Service
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ICategoryRepository categoryRepository;
    @Override
    public void addNew(CategoryAddNewDTO categoryAddNewDTO) {
        String name=categoryAddNewDTO.getName();
        int count=categoryMapper.countByName(name);
        if (count>0){
            String message="添加类别失败，类别名称【" + name + "】已经被占用！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }

        Category category=new Category();

        BeanUtils.copyProperties(categoryAddNewDTO,category);

        log.debug("即将向表中写入数据：{}", category);
        LocalDateTime now=LocalDateTime.now();
        category.setGmtCreate(now);
        int rows = categoryMapper.insert(category);
        if (rows != 1) {
            String message = "添加类别失败，服务器忙，请稍后再次尝试！【错误码：1】";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理删除类别的业务");
        CategoryDetailVO categoryDetailVO=categoryMapper.getById(id);
        if (categoryDetailVO==null){
            String message="删除失败"+id+"不存在";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
        int count=categoryMapper.articleCountById(id);
        if (count>0){
            String message="删除失败，该类别还有文章，不可以删除";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
        int rows=categoryMapper.deleteById(id);
        if (rows!=1){
            String message="删除失败，请联系管理员";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
    }

    @Override
    public int deleteByIds(Long[] ids) {
        List<CategoryDetailVO> list = categoryMapper.selectByids(ids);
        for (CategoryDetailVO detailVO : list) {
            String name = detailVO.getName();
            OssUtils.delete(name);
        }
        log.debug("开始处理批量删除分类的业务:");
        int rows = categoryMapper.deleteByIds(ids);
        return rows;
    }

    @Override
    public int articleCount(Long id) {
        log.debug("开始处理查询文章数的业务:");
        return categoryMapper.ArticleCount(id);
    }

    @Override
    public List<CategoryListVO> listByCategory(CategoryListVO categoryListVO) {
        log.debug("准备开始处理条件分页查询类别的业务，参数：{}", categoryListVO);
        return categoryMapper.listByCategory(categoryListVO);

    }

    @Override
    public void updateById(Long id,CategoryAddDTO categoryAddDTO) {
        log.debug("开始处理修改分类的业务");
        CategoryDetailVO cate = categoryMapper.getById(id);
        if (cate == null) {
            String message = "修改分类失败，尝试修改的分类(id=" + id + ")不存在";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryAddDTO,category);
        int rows = categoryMapper.updateById(categoryAddDTO);
        if (rows != 1) {
            String message = "修改分类失败,服务器忙,请稍后重试";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public CategoryDetailVO categorySelect(Long id) {
        log.debug("正在执行查询");
        CategoryDetailVO categoryDetailVO=categoryMapper.selectById(id);
        return categoryDetailVO;
    }

    @Override
    public List<CategoryListVO> list() {
        log.debug("开始处理查询类别的业务");
        return categoryMapper.list();
    }


    @Override
    public int getCountAll(CategoryListVO categoryListVO) {
        log.debug("准备开始处理条件查询结果集数量的业务，参数：{}", categoryListVO);
        return categoryMapper.getCountAll(categoryListVO);
    }


    /*前台分类列表查询*/
    @Override
    public List<CategoryListVO> AllList() {

            boolean isExpired= categoryRepository.isExpired(KEY_CATEGORY_LIST );
            if(isExpired){
                log.debug("====执行数据库查询存入redis====");
                List<CategoryListVO> list =categoryMapper.listAll();
                if(list==null){
                    throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"数据库中没有分类");
                }
                categoryRepository.putList(list,KEY_CATEGORY_LIST);
                return list;
            }else {
                return categoryRepository.getList(KEY_CATEGORY_LIST);
            }
        }


}
